import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class ChatClient {
    public ChatClient(){
        try {
            Socket socket = new Socket("localhost",9900);
            //提示用户输入姓名并处理用户在控制台输入的姓名
            System.out.println("请输入您的姓名:");
            //使用Scanner实现从控制台输入
            Scanner sc = new Scanner(System.in);
            String name = sc.nextLine();

            //获得与服务器端通信的输出流对象，并向服务器端发送姓名
            OutputStream os = socket.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(os);
            oos.writeObject(name);

            //接收服务器端的消息并在控制台输出
            InputStream is = socket.getInputStream();
            ObjectInputStream ois = new ObjectInputStream(is);
            System.out.println(ois.readObject());
                new Thread(){
                    @Override
                    public void run() {
                        while (true) {
                            String msg = sc.nextLine();
                            try {
                                oos.writeObject(msg);
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }

                        }
                    }
                }.start();
                new Thread(){
                    @Override
                    public void run() {
                        while (true) {

                            try {
                                System.out.println(ois.readObject());
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            } catch (ClassNotFoundException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                }.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
    public static void main(String[] args) {
        new ChatClient();
    }
}
